package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.adapter.ThemBoSuuTapAdapter;
import com.vnp.cooking.bean.ObjBST;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ThemVaoBoSuuTapActivity extends Activity implements
		OnClickListener, OnItemClickListener {

	PreferenceHelper preferenceHelper;
	
	Button btnThemBST;
	ImageButton btnBack;
	EditText editThemBST;
	ListView listBST;
	ThemBoSuuTapAdapter adapter;
	ArrayList<ObjBST> objBSTs = new ArrayList<ObjBST>();
	
	EasyTracker easyTracker;
	
	// dialog them thanh cong
	Dialog d;
	ObjCookpad objCookpad = new ObjCookpad();
	
	// load bo suu tap
	ProgressBar progressbar;
	TextView noBST;
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	Handler mHandler = new Handler();
	ProgressDialog progressDialog;
	
	TextView title, titleBosutapDatao;
	
	private static final String SCREEN_LABEL = "Them bo suu tap screen";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_them_vao_bo_suu_tap);
		easyTracker = EasyTracker.getInstance(this);
		
		preferenceHelper = new PreferenceHelper(this);
		
		objCookpad = getIntent().getParcelableExtra("objCookpad");
		
		
		title = (TextView) findViewById(R.id.title_themvaobosuutap);
		titleBosutapDatao = (TextView) findViewById(R.id.title_bst_datao);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnThemBST = (Button) findViewById(R.id.btn_themmoi_bst);
		editThemBST = (EditText) findViewById(R.id.edt_nhap_ten_bst);
		progressbar = (ProgressBar) findViewById(R.id.progressBarGetBST);
		noBST = (TextView) findViewById(R.id.no_bst);
		listBST = (ListView) findViewById(R.id.list_ten_bst);
		adapter = new ThemBoSuuTapAdapter(this, objBSTs);

		setFont();
		
		init();
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);

	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}
	
	private void setFont() {
		title.setTypeface(Utils.getTypefaceRegular(ThemVaoBoSuuTapActivity.this), Typeface.BOLD);
		btnThemBST.setTypeface(Utils.getTypefaceRegular(ThemVaoBoSuuTapActivity.this));
		titleBosutapDatao.setTypeface(Utils.getTypefaceRegular(ThemVaoBoSuuTapActivity.this), Typeface.BOLD);
		editThemBST.setTypeface(Utils.getTypefaceRegular(ThemVaoBoSuuTapActivity.this));
	}
	
	void init() {
		getBST();
		
		btnBack.setOnClickListener(this);
		btnThemBST.setOnClickListener(this);
		listBST.setAdapter(adapter);
		listBST.setOnItemClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			closeActivity();
			break;
		case R.id.btn_themmoi_bst:
			KeyboardHelper.hideSoftKeyboard(ThemVaoBoSuuTapActivity.this);
			addBosuutap();
			break;
		case R.id.btn_tieptuc_bst:
			d.dismiss();
			getBST();
			mHandler.postDelayed(r, 200);
			break;
		default:
			break;
		}
	}

	// add them bo suu tap
	public void addBosuutap() {
		if (editThemBST.getText().toString().matches("")) {

		} else {
			ObjBST objBST = new ObjBST(editThemBST.getText().toString());
			objBSTs.add(objBST);
			progressDialog = ProgressDialog.show(ThemVaoBoSuuTapActivity.this, "", "Đang thêm món ăn vào bộ sưu tập...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			// gui api tao moi kem gia tri mon an moi len
			creatNewBST();
			editThemBST.setText("");
			adapter.notifyDataSetChanged();
			
			
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		// gui api tao moi kem gia tri mon an moi len
		progressDialog = ProgressDialog.show(ThemVaoBoSuuTapActivity.this, "", "Đang thêm món ăn vào bộ sưu tập...");
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (null != progressDialog && progressDialog.isShowing())
					progressDialog.dismiss();
			}
		}, 90000);
		String collection = objBSTs.get(position).getCollection_id();
		updateBST(objCookpad.getId(), collection);
	}

	// show dialog sau khi them thanh cong
	public void showDialogThemThanhcong() {
		d = new Dialog(this);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.dialog_them_thanhcong);
		
		Button btnTieptucThem = (Button) d.findViewById(R.id.btn_tieptuc_bst);
		d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		d.setCanceledOnTouchOutside(true);
		d.getWindow().setGravity(Gravity.CENTER);
		d.show();
		
		// setonclick
		btnTieptucThem.setOnClickListener(this);
	}
	
	
	/** Bo suu tap */
	public void creatNewBST() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressDialog.dismiss();
				Toast.makeText(ThemVaoBoSuuTapActivity.this, "Không kết nối được với server...", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					progressDialog.dismiss();
					if (status == 200) {
						easyTracker.send(MapBuilder.createEvent("CONGTHUC", "GHIM", "THEM VAO BO SUU TAP", null).build());
						ChitietCongthucActivity.pinned = 1;
						showDialogThemThanhcong();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		httpClientHelper.createNewBST(preferenceHelper.getID(), editThemBST.getText().toString(), objCookpad.getId());
	}
	
	// get danh sach bo suu tap
	void getBST() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressbar.setVisibility(View.GONE);
				noBST.setVisibility(View.VISIBLE);
				noBST.setText("Không lấy được bộ sưu tập");
			}

			@Override
			public void onSuccess(JSONObject re) {
				progressbar.setVisibility(View.GONE);
				if (!re.toString().equals("")) {
					preferenceHelper.setCacheBosuutap(re.toString());
				}
				parserData(re);
				
			}
			
		});
		httpClientHelper.getBST(preferenceHelper.getID());
	}
	
	public void parserData(JSONObject re) {
		int status;
		try {
			status = re.getInt("status");
			if (status == 200) {
				adapter.clear();
				JSONArray data = re.getJSONArray("data");
				Log.i("DATA", data.toString());
				if (data.length() == 0) {
					noBST.setVisibility(View.VISIBLE);
				}
				for (int i = 0; i < data.length(); i++) {
					JSONObject collection = data.getJSONObject(i);
					ObjBST objBST = new ObjBST();
					objBST.setCollection_id(collection.getString("collection_id"));
					objBST.setName(collection.getString("name"));
					objBST.setSoluong(collection.getInt("total_items"));
					
					objBSTs.add(objBST);
				}
				adapter.notifyDataSetChanged();
				
			} else {
				progressbar.setVisibility(View.GONE);
				noBST.setVisibility(View.VISIBLE);
				noBST.setText("Không lấy được bộ sưu tập");
			}
		} catch (JSONException e) {
			e.printStackTrace();
			progressbar.setVisibility(View.GONE);
			noBST.setVisibility(View.VISIBLE);
			noBST.setText("Không lấy được bộ sưu tập");
		}
	}
	
	void loadCache() {
		String cache = preferenceHelper.getCacheBosuutap();
		if(!cache.equals("")) {
			try {
				JSONObject response = new JSONObject(cache);
				parserData(response);
			} catch (Exception e) { }
		}
	}

	
	// update bo suu tap
	void updateBST(String recipe_id, String collection_id) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressDialog.dismiss();
				Toast.makeText(ThemVaoBoSuuTapActivity.this, "Không kết nối được với server...", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					progressDialog.dismiss();
					if(status == 200) {
						easyTracker.send(MapBuilder.createEvent("CONGTHUC", "GHIM", "THEM VAO BO SUU TAP", null).build());
						ChitietCongthucActivity.pinned = 1;
						showDialogThemThanhcong();
					} else {
						Toast.makeText(ThemVaoBoSuuTapActivity.this, "Thêm thất bại. Vui lòng thử lại.", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		httpClientHelper.updateBST(preferenceHelper.getID(), recipe_id, collection_id);
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}


	@Override
	public void onBackPressed() {
		closeActivity();
	}
}
